<script setup lang="ts">
import type { Choice } from '@/api/subject/type';
import { ref, watch, computed } from 'vue';

const props = defineProps<{
  choice: Choice;
  modelValue: string | string[]; 
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | string[]): void;
}>();

const raw = ref<string | string[]>(props.modelValue);
// const answer = ref(props.modelValue);

// 更新答案
// const updateAnswer = (value: string | string[]) => {
//   answer.value = value;
//   emit('update:modelValue', value);
// };

watch(
  () => props.modelValue,
  v => (raw.value = v)
);

const single = computed<string>({
  get: () =>
    typeof raw.value === 'string' ? raw.value : '',     // 非 string 时给空串
  set: v => {
    raw.value = v;
    emit('update:modelValue', v);
  }
});

const multi = computed<string[]>({
  get: () =>
    Array.isArray(raw.value) ? raw.value : [],          // 非数组时给空数组
  set: v => {
    raw.value = v;
    emit('update:modelValue', v);
  }
});
</script>


<template>
  <van-cell-group inset>
    <!-- 判断是否为多选 -->
    <van-radio-group v-if="!choice.isMultiple" v-model="single" >
      <van-cell v-for="(option, index) in choice.options" :key="index">
        <template #title>
          <van-radio :name="option">{{ option }}</van-radio>
        </template>
      </van-cell>
    </van-radio-group>

    <van-checkbox-group v-else v-model="multi" >
      <van-cell v-for="(option, index) in choice.options" :key="index">
        <template #title>
          <van-checkbox :name="option">{{ option }}</van-checkbox>
        </template>
      </van-cell>
    </van-checkbox-group>
  </van-cell-group>
</template>
